package com.correo.database.server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import com.correo.database.beans.Configuracion;
import com.correo.database.beans.DataBaseBean;
import com.correo.modelo.server.ModelOficce;

public class ManagerDataBase {

	private static ManagerDataBase 			managerDataBase;
	private Connection						connection;
	private ManagerDataBaseUser				dataBaseUser;
	private ManagerDataBaseOffice			dataBaseOffice;
	private ManagerDataBaseCasillaCorreo 	dataBaseCasillaCorreo;
	
	public static ManagerDataBase getInstance() throws ClassNotFoundException, SQLException{
		if(managerDataBase==null){
			managerDataBase = new ManagerDataBase();
			
		}
		return managerDataBase;
	}
	
	private ManagerDataBase() throws ClassNotFoundException, SQLException{
		setConnection();
		dataBaseUser=new ManagerDataBaseUser(getConnection());
		dataBaseOffice = new ManagerDataBaseOffice(getConnection());
		dataBaseCasillaCorreo = new ManagerDataBaseCasillaCorreo(getConnection());
	}
	
	public Connection getConnection() throws SQLException, ClassNotFoundException{
		if(connection==null || connection.isClosed()){
			setConnection();
		}
		return connection;
	}

	private void setConnection() throws ClassNotFoundException, SQLException {		        	
		Class.forName(Configuracion.DRIVER);
        connection = DriverManager.getConnection(Configuracion.URL,Configuracion.USER,Configuracion.PASSWORD);
	}
	
	//ejecutando los sql
	
	public List<DataBaseBean> select(DataBaseBean dataBaseBean) throws SQLException, ClassNotFoundException{
		
		PreparedStatement preparedStatement = getConnection().prepareCall(dataBaseBean.getSelect());
		dataBaseBean.setPreparedSql(preparedStatement);
		
		return getResult(dataBaseBean,preparedStatement.executeQuery());
	}

	private List<DataBaseBean> getResult(DataBaseBean dataBaseBean, ResultSet result) throws SQLException {
		List<DataBaseBean> listResult=new LinkedList<DataBaseBean>();
		
		while(result.next()){
			listResult.add(dataBaseBean.getDataBean(result));
		}
		return listResult;
	}
	
	public List<DataBaseBean> insert(DataBaseBean dataBaseBean) throws SQLException, ClassNotFoundException{
		PreparedStatement preparedStatement = getConnection().prepareCall(dataBaseBean.getInsert());
		dataBaseBean.setPreparedSql(preparedStatement);
		
		return null;
	}

	public ManagerDataBaseUser getMngUserDataBase() {		
		return this.dataBaseUser;
	}

	public ManagerDataBaseOffice getMngOfficeDataBase() {
		return dataBaseOffice;
	}
	public ManagerDataBaseCasillaCorreo getMngCasillaCorreoDataBase() {
		return dataBaseCasillaCorreo;
	}
}
